using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FiltronASP.Models;
using FiltronASP.Models.DAO;
using FiltronASP.Models.DAO.Interfaces;
using FiltronASP.Models.DAO.WIX;
using FiltronASP.Models.DAO.Interfaces.WIX;
using FiltronASP.Models.DAO.Filtron;
using FiltronASP.Models.DAO.Interfaces.Filtron;
using FiltronASP.Helpers.Constants;
using System.Text.RegularExpressions;
using FiltronASP.Helpers.CatalogueHelpers;
using FiltronASP.Helpers.Translations;

namespace FiltronASP.Helpers.ReplacementsHelper
{
    public class MultisearchReplacementList
    {
        private static List<Replacement> replacementList = new List<Replacement>();
        private static List<String> HelperList = new List<String>();

        private static Boolean findInFiltronByWixFilterNumber(string searchFilterNumber, Constants.Constants.TSearchInclusionMode searchMode, int limit)
        {
            Boolean sthFound = false;
            IFiltronFilterDAO filtronFilterDAO = new FiltronFilterDAO();
            IQueryable<FiltronFilter> filtronFiltersList = null;
            if (limit > 0)
            {
                filtronFiltersList = filtronFilterDAO.FindByWixFilterNumberContains(searchFilterNumber, searchMode, limit);
            }
            else
            {
                filtronFiltersList = filtronFilterDAO.FindByWixFilterNumberContains(searchFilterNumber, searchMode);
            }
            if (filtronFiltersList != null)
            {
                foreach (FiltronFilter singleFiltronFilter in filtronFiltersList)
                {
                    String filterNumber = String.Empty;
                    if (String.IsNullOrEmpty(singleFiltronFilter.filter_wix_number))
                    {
                        filterNumber = singleFiltronFilter.filter_wix_number_hd;
                    }   //if hd only
                    else if (String.IsNullOrEmpty(singleFiltronFilter.filter_wix_number_hd))
                    {
                        filterNumber = singleFiltronFilter.filter_wix_number;
                    }   //else not hd only
                    else
                    {
                        filterNumber = singleFiltronFilter.filter_wix_number + "<br/>" + singleFiltronFilter.filter_wix_number_hd;
                    }   //else
                    if (!String.IsNullOrEmpty(filterNumber))
                    {
                        Replacement singleReplacement = new Replacement();
                        singleReplacement.foreignFilter = FiltronHelper.GetFiltronFilterWixNumber(singleFiltronFilter.filter_wix_number, singleFiltronFilter.filter_wix_number_hd);
                        singleReplacement.foreignFilterManufacturer = "WIX";
                        singleReplacement.ownFilterProducer = "F";
                        singleReplacement.ownFilterId = singleFiltronFilter.filter_id;
                        singleReplacement.ownFilterNumber = filterNumber;
                        string stringToCheck = removeSpecialCharacters(singleReplacement.foreignFilter + singleReplacement.ownFilterNumber + "WIX");
                        if (!(HelperList.Contains(stringToCheck)))
                        {
                            replacementList.Add(singleReplacement);
                            HelperList.Add(stringToCheck);
                            sthFound = true;
                        }   //if
                    }   //if
                }
            }
            return sthFound;
        }

        private static Boolean findInFiltronByInterchangeNumber(string searchFilterNumber, Constants.Constants.TSearchInclusionMode searchMode, int limit)
        {
            Boolean sthFound = false;
            IFiltronFilterDAO filtronFilterDAO = new FiltronFilterDAO();
            IFiltronInterchangeDAO filtronInterchangeDAO = new FiltronInterchangeDAO();
            IFiltronInterchangeManufacturerDAO filtronInterchangeManufacturerDAO = new FiltronInterchangeManufacturerDAO();
            IQueryable<FiltronInterchange> filtronInterchangesCollection = null;
            if (limit > 0)
            {
                filtronInterchangesCollection = filtronInterchangeDAO.FindByForeignFilterNameLimited(searchFilterNumber, searchMode, limit);
            }
            else
            {
                filtronInterchangesCollection = filtronInterchangeDAO.FindByForeignFilterNameLimited(searchFilterNumber, searchMode);
            }
            if (filtronInterchangesCollection != null)
            {
                foreach (FiltronInterchange singleFiltronInterchange in filtronInterchangesCollection)
                {
                    String manufacturerName = filtronInterchangeManufacturerDAO.FindByPK(singleFiltronInterchange.manufacturer_id).manufacturer_name;
                    FiltronFilter filterEntity = filtronFilterDAO.FindByPK(singleFiltronInterchange.filter_id);
                    String filterNumber = String.Empty;
                    if (String.IsNullOrEmpty(filterEntity.filter_wix_number))
                    {
                        filterNumber = filterEntity.filter_wix_number_hd;
                    }   //if hd only
                    else if (String.IsNullOrEmpty(filterEntity.filter_wix_number_hd))
                    {
                        filterNumber = filterEntity.filter_wix_number;
                    }   //else not hd only
                    else
                    {
                        filterNumber = filterEntity.filter_wix_number + "<br/>" + filterEntity.filter_wix_number_hd;
                    }   //else
                    if (!String.IsNullOrEmpty(filterNumber))
                    {
                        Replacement singleReplacement = new Replacement();
                        singleReplacement.foreignFilter = singleFiltronInterchange.foreign_filter_number;
                        singleReplacement.foreignFilterManufacturer = manufacturerName;
                        singleReplacement.ownFilterProducer = "F";
                        singleReplacement.ownFilterId = singleFiltronInterchange.filter_id;
                        singleReplacement.ownFilterNumber = filterNumber;
                        string stringToCheck = removeSpecialCharacters(singleReplacement.foreignFilter + singleReplacement.ownFilterNumber + manufacturerName); 
                        if (!(HelperList.Contains(stringToCheck)))
                        {
                            replacementList.Add(singleReplacement);
                            HelperList.Add(stringToCheck);
                            sthFound = true;
                        }
                    }   //if
                }
            }
            return sthFound;
        }

        private static Boolean findInWixByWixFilterNumber(string searchFilterNumber, Constants.Constants.TSearchInclusionMode searchMode, int limit)
        {
            Boolean sthFound = false;
            IWixFilterDAO wixFilterDAO = new WixFilterDAO();
            IQueryable<WixFilter> wixFiltersList = null;
            if (limit > 0)
            {
                wixFiltersList = wixFilterDAO.FindByFilterNumber(searchFilterNumber, searchMode, limit);
            }
            else
            {
                wixFiltersList = wixFilterDAO.FindByFilterNumber(searchFilterNumber, searchMode);
            }
            if (wixFiltersList != null)
            {
                foreach (WixFilter singleWixFilter in wixFiltersList)
                {
                    Replacement singleReplacement = new Replacement();
                    singleReplacement.foreignFilter = singleWixFilter.filter_number;
                    singleReplacement.foreignFilterManufacturer = "WIX";
                    singleReplacement.ownFilterProducer = "W";
                    singleReplacement.ownFilterId = singleWixFilter.filter_id;
                    singleReplacement.ownFilterNumber = singleWixFilter.filter_number;
                    string stringToCheck = removeSpecialCharacters(singleReplacement.foreignFilter + singleReplacement.ownFilterNumber + "WIX");
                    if (!(HelperList.Contains(stringToCheck)))
                    {
                        replacementList.Add(singleReplacement);
                        HelperList.Add(stringToCheck);
                        sthFound = true;
                    }
                }
            }
            return sthFound;
        }

        private static Boolean findInWixByInterchangeNumber(string searchFilterNumber, Constants.Constants.TSearchInclusionMode searchMode, int limit)
        {
            Boolean sthFound = false;
            IWixFilterDAO wixFilterDAO = new WixFilterDAO();
            IWixInterchangeDAO wixInterchangeDAO = new WixInterchangeDAO();
            IWixInterchangeManufacturerDAO wixInterchangeManufacturerDAO = new WixInterchangeManufacturerDAO();
            IQueryable<WixInterchange> wixInterchangesCollection = null;
            if (limit > 0)
            {
                wixInterchangesCollection = wixInterchangeDAO.FindByForeignFilterNameLimited(searchFilterNumber, searchMode, limit);
            }
            else
            {
                wixInterchangesCollection = wixInterchangeDAO.FindByForeignFilterNameLimited(searchFilterNumber, searchMode);
            }
            if (wixInterchangesCollection != null)
            {
                foreach (WixInterchange singleWixInterchange in wixInterchangesCollection)
                {
                    String manufacturerName = wixInterchangeManufacturerDAO.FindByPK(singleWixInterchange.manufacturer_id).manufacturer_name;
                    String filterNumber = wixFilterDAO.FindByPK(singleWixInterchange.filter_id).filter_number;
                    Replacement singleReplacement = new Replacement();
                    singleReplacement.foreignFilter = singleWixInterchange.foreign_filter_number;
                    singleReplacement.foreignFilterManufacturer = manufacturerName;
                    singleReplacement.ownFilterProducer = "W";
                    singleReplacement.ownFilterId = singleWixInterchange.filter_id;
                    singleReplacement.ownFilterNumber = filterNumber;
                    string stringToCheck = removeSpecialCharacters(singleReplacement.foreignFilter + singleReplacement.ownFilterNumber + manufacturerName);
                    if (!(HelperList.Contains(stringToCheck)))
                    {
                        replacementList.Add(singleReplacement);
                        HelperList.Add(stringToCheck);
                        sthFound = true;
                    }
                }
            }
            return sthFound;
        }

        public static string generateReplacementList(string typedValues, string languageName) {
            replacementList.Clear();
            HelperList.Clear();
            typedValues = removeSpecialCharacters(typedValues);
            if (!validateQueryLength(typedValues)) 
            {
                return "state:queryTooShort";
            }
            string[] splittedTypeValues = typedValues.Split(',');
            if (splittedTypeValues.Length > 15)
            {
                return "state:queryTooLong";
            }   //if
            foreach (string typedValue in splittedTypeValues)
            {
                Boolean sthFound = false;
                if (!typedValue.Contains('*'))
                {                                  
                    sthFound |= findInFiltronByWixFilterNumber(typedValue, Constants.Constants.TSearchInclusionMode.simExact, 0);
                    sthFound |= findInWixByWixFilterNumber(typedValue, Constants.Constants.TSearchInclusionMode.simExact, 0);
                    sthFound |= findInFiltronByInterchangeNumber(typedValue, Constants.Constants.TSearchInclusionMode.simExact, 0);
                    sthFound |= findInWixByInterchangeNumber(typedValue, Constants.Constants.TSearchInclusionMode.simExact, 0);
                    if (sthFound == true)
                    {
                        continue;
                    }
                    sthFound |= findInWixByInterchangeNumber(typedValue, Constants.Constants.TSearchInclusionMode.simBoth, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                    sthFound |= findInFiltronByInterchangeNumber(typedValue, Constants.Constants.TSearchInclusionMode.simBoth, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                }   //if not *
                else
                {
                    if ((typedValue.StartsWith("*")) && (typedValue.EndsWith("*")))
                    {
                        String searchValue = typedValue.Replace("*", String.Empty);
                        sthFound |= findInFiltronByWixFilterNumber(searchValue, Constants.Constants.TSearchInclusionMode.simBoth, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                        sthFound |= findInWixByWixFilterNumber(searchValue, Constants.Constants.TSearchInclusionMode.simBoth, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                        sthFound |= findInWixByInterchangeNumber(searchValue, Constants.Constants.TSearchInclusionMode.simBoth, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                        sthFound |= findInFiltronByInterchangeNumber(searchValue, Constants.Constants.TSearchInclusionMode.simBoth, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                    }   //if
                    else if (typedValue.StartsWith("*"))
                    {
                        String searchValue = typedValue.Replace("*", String.Empty);
                        sthFound |= findInFiltronByWixFilterNumber(searchValue, Constants.Constants.TSearchInclusionMode.simRight, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                        sthFound |= findInWixByWixFilterNumber(searchValue, Constants.Constants.TSearchInclusionMode.simRight, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                        sthFound |= findInWixByInterchangeNumber(searchValue, Constants.Constants.TSearchInclusionMode.simRight, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                        sthFound |= findInFiltronByInterchangeNumber(searchValue, Constants.Constants.TSearchInclusionMode.simRight, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                    }   //else
                    else if (typedValue.EndsWith("*"))
                    {
                        String searchValue = typedValue.Replace("*", String.Empty);
                        sthFound |= findInFiltronByWixFilterNumber(searchValue, Constants.Constants.TSearchInclusionMode.simLeft, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                        sthFound |= findInWixByWixFilterNumber(searchValue, Constants.Constants.TSearchInclusionMode.simLeft, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                        sthFound |= findInWixByInterchangeNumber(searchValue, Constants.Constants.TSearchInclusionMode.simLeft, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                        sthFound |= findInFiltronByInterchangeNumber(searchValue, Constants.Constants.TSearchInclusionMode.simLeft, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                    }   //else
                    else
                    {
                        String searchValue = typedValue.Replace("*", String.Empty);
                        sthFound |= findInFiltronByWixFilterNumber(searchValue, Constants.Constants.TSearchInclusionMode.simBoth, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                        sthFound |= findInWixByWixFilterNumber(searchValue, Constants.Constants.TSearchInclusionMode.simBoth, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                        sthFound |= findInWixByInterchangeNumber(searchValue, Constants.Constants.TSearchInclusionMode.simBoth, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                        sthFound |= findInFiltronByInterchangeNumber(searchValue, Constants.Constants.TSearchInclusionMode.simBoth, Constants.Constants._MULTISEARCH_RESULTS_LIMIT);
                    }   //else
                }   //else not *
            }   //for
            if (replacementList.Any()) {
                return generateDataToTable(replacementList, languageName);
            }
            return translationHelper.getTranslation("_ajaxNoReplacements", languageName);
        }


        private static string generateDataToTable(List<Replacement> replacementList, string languageName)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<div class='col-xs-12 no-padding overlay-engine overlay-engine-boder-b'>");
            sb.Append("<div class='col-xs-4 no-padding overlay-engine-boder-r'>");
            sb.Append("<p>" + FiltronASP.Helpers.Translations.translationHelper.getTranslation("_repForeignFilter", languageName) + "</p>");
            sb.Append("</div>");
            sb.Append("<div class='col-xs-4 no-padding overlay-engine-boder-r'>");
            sb.Append("<p >" + FiltronASP.Helpers.Translations.translationHelper.getTranslation("_repManufacturerName", languageName) + "</p>");
            sb.Append("</div>");

            sb.Append("<div class='col-xs-4 no-padding overlay-engine-boder-r'>");
            sb.Append("<p >" + FiltronASP.Helpers.Translations.translationHelper.getTranslation("_repReplacementFilter", languageName) + "</p>");
            sb.Append("</div>");
            sb.Append("</div>");
            sb.Append("<div id =\"filtersTable\">");
            foreach (var replacement in replacementList)
            {
                sb.Append("<div class=\"col-xs-12 no-padding overlay-engine engine-hover overlay-engine-boder-b filter-selector \"   data-model=\"" + replacement.foreignFilter + "\"  data-filter=\"" + replacement.ownFilterId + "\" data-rep=\"" + replacement.ownFilterProducer + "\"   \">");
                sb.Append("<div class=\"col-xs-4 no-padding overlay-engine-boder-r\">");
                sb.Append("<p class=\"overlay-cross engine-info-normal\">" + replacement.foreignFilter + "</p>");
                sb.Append("</div>");
                sb.Append("<div class=\"col-xs-4 no-padding overlay-engine-boder-r\">");
                sb.Append("<p class=\"overlay-cross engine-info-normal\">" + replacement.foreignFilterManufacturer + "</p>");
                sb.Append("</div>");
                sb.Append("<div class=\"col-xs-4 no-padding overlay-engine-boder-r\">");
                sb.Append("<p class=\"overlay-cross engine-info-normal\">" + replacement.ownFilterNumber + "</p>");
                sb.Append("</div>");
                sb.Append("</div>");
            }
            sb.Append("</div>");
            return sb.ToString();
        }



      /*  private static string generateDataToTable(List<Replacement> replacementList, string languageName)
        {
            String dataString = String.Empty;
            String jSONToRet = String.Empty;
            foreach (Replacement singleReplacement in replacementList) {
                dataString += String.Format("{{\"{5}\": \"{0}\", \"{7}\": \"{3}\", \"repId\": \"{2}\", \"{6}\": \"{1}\", \"repFilterProd\": \"{4}\"}},", singleReplacement.foreignFilter, singleReplacement.ownFilterNumber, singleReplacement.ownFilterId, singleReplacement.foreignFilterManufacturer, singleReplacement.ownFilterProducer, Helpers.Translations.translationHelper.getTranslation("_repForeignFilter", languageName), Helpers.Translations.translationHelper.getTranslation("_repReplacementFilter", languageName), Helpers.Translations.translationHelper.getTranslation("_repManufacturerName", languageName));
            }
            jSONToRet = String.Format("{{\"bindings\": [{0}]}}", dataString.Remove(dataString.Length - 1, 1));
            return jSONToRet;
        }*/

        private static bool validateQueryLength(string query)
        {
            Regex rgx = new Regex("[^a-zA-Z0-9]");
            query = rgx.Replace(query, ""); 
            if (query.Length < 2)
            {
                return false;
            }   //if
            return true;
        }

        private static string removeSpecialCharacters(string value)
        {
            if (String.IsNullOrEmpty(value))
            {
                return String.Empty;
            }   //if
            return Regex.Replace(value, @"[^a-zA-Z0-9\*_,.]+", "", RegexOptions.Compiled);
        }
    }
}
